const mysql = require('mysql');
const config = require('../../config');
const pool = mysql.createPool({
  database: 'flower',
  ...config,
});

exports.query = (query, values) => {
  return new Promise((resolve, reject) => {
    pool.query(query, values, (err, records) => {
      if (err) return reject(err);
      resolve(records);
    });
  });
}

exports.create = (name, data) => {
  return new Promise((resolve, reject) => {
    pool.query('insert into `' + name + '` set ?', [data], (err, records) => {
      if (err) return reject(err);
      data.id = records.insertId;
      resolve(data);
    });
  });
}

exports.update = (name, data) => {
  return new Promise((resolve, reject) => {
    pool.query('update `' + name + '` set ? where id=?', [data, data.id], err => {
      if (err) return reject(err);

      pool.query('select * from `' + name + '` where id=? limit 1', [data.id], (err, records) => {
        if (err) return reject(err);
        if (records.length === 0) return reject('资源不存在');
        
        resolve(records[0]);
      });
    });
  });
}

exports.get = (name, id) => {
  return new Promise((resolve, reject) => {
    pool.query('select * from `' + name + '` where id=? limit 1', [id], (err, records) => {
      if (err) return reject(err);
      if (records.length === 0) return reject(new Error('资源不存在'));

      resolve(records[0]);
    });
  });
}

exports.del = (name, id) => {
  return new Promise((resolve, reject) => {
    pool.query('delete from `' + name + '` where id=?', [id], err => {
      if (err) return reject(err);
      resolve(null);
    });
  });
}
